<?php
/*!
 * CSSOptimizer - CSS minify and optimize library
 * 
 * Copyright 2010, Anton Ilyuschenkov aka DriverX
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://driverx.su/license.html
 */


/*
ini_set('register_globals', 'Off');
ini_set('magic_quotes_gpc', 'Off');
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');
ini_set('error_reporting', E_ALL);
ini_set('zlib.output_compression', 'On');
*/


interface iCSSOptimizer {
	public function whitespace ();
	public function optimize ();
	public function write ();
	public function writeFile ($filename = '');
}

class clCSSOptimizer implements iCSSOptimizer {
	public $source = '';
	public $cssText = null;
	public $cssTextOptimized = null;
	protected $isCutWhitespace = false;
	protected $isOptimized = false;
	public function __construct ($source = '', $flags = '') {
		$source = (string) $source;
		$this->source = $source;
		if (preg_match('/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/', $source)) {
			$cssText = file_get_contents($source);
			if ($cssText === false) {
				throw new ErrorException('Can\'t open file '.$source.'!');
			}
		} else {
			$cssText = $source;
		}
		if (!$source) {
			throw new ErrorException('source is empty');
		}
		$this->cssText = $cssText;
	}
	public function whitespace() {
		if (!$this->isCutWhitespace) {
			$cssText = $this->cssText;
			$cssText = preg_replace('/(?<!["\'\s])\s+(?!["\'\s])/', ' ', $cssText);
			$cssText = preg_replace('/\/\*[^*]*\*+([^\/*][^*]*\*+)*\//', '', $cssText);
			$cssText = preg_replace('/^\s+/', '', $cssText);
			$cssText = preg_replace('/\s+$/', '', $cssText);
			$cssText = preg_replace('/\s+(?=[{}])|(?<=[\s:;{},])\s+/', '', $cssText);
			$this->cssTextOptimized = $cssText;
			$this->isCutWhitespace = true;
		}
	}
	public function optimize() {
		$this->whitespace();
		if (!$this->isOptimized) {
			$cssText = $this->cssTextOptimized;
			$cssText = preg_replace('/;(?=[}])/', '', $cssText);
			$cssText = preg_replace('/(?<=[\s:])0(?:em|ex|px|in|mm|pt|pc|%)/', '0', $cssText);
			$cssText = preg_replace('/(?<=[\s:])0(?=\.\d)/', '', $cssText);
			$cssText = preg_replace('/#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3/i', '#\1\2\3', $cssText);
			$this->cssTextOptimized = $cssText;
			$this->isOptimized = true;
		}
	}
	public function write () {
		echo $this->cssTextOptimized !== null ? $this->cssTextOptimized : $this->cssText;
	}
	public function writeFile ($filename = '') {
		
	}
}

$CSSOptimizer = new clCSSOptimizer('./tests/test2.css');
$CSSOptimizer->optimize();
$CSSOptimizer->write();

?>